package pers.whj.net.local.tools;

import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class NetworkTools {
    public static List<InetAddress> getAllIPv4() throws UnknownHostException {
        InetAddress[] inetAddresses = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
        List<InetAddress> addressList = new ArrayList<>();
        for (InetAddress inetAddress : inetAddresses) {
            if (inetAddress.getAddress().length == 4) {
                addressList.add(inetAddress);
            }
        }
        return addressList;
    }

    public static List<InetAddress> getLANAddressOnWindows() throws UnknownHostException, SocketException {
        List<InetAddress> addressList = getAllIPv4();
        for (int i = 0; i < addressList.size(); i++) {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(addressList.get(i));
            if (!networkInterface.getName().startsWith("wlan")) {
                addressList.remove(i);
                i--;
            }
        }
        return addressList;
    }

    public static List<String> getBroadcastAddresses() throws SocketException {
        List<String> result = new ArrayList<>();
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            if (networkInterface.isUp() && !networkInterface.isLoopback()) {
                List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
                for (InterfaceAddress address : interfaceAddresses) {
                    if (address.getAddress().getAddress().length == 4) {
                        String broadcast = address.getBroadcast().getHostAddress();
                        if (result.contains(broadcast)) {
                            continue;
                        }
                        if (networkInterface.getName().startsWith("wlan")) {
                            result.add(0, broadcast);
                        } else {
                            result.add(broadcast);
                        }
                    }
                }
            }
        }
        return result;
    }
}